package org.medicine.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.medicine.util.MysqlOperation;
import org.medicine.vo.FileVO;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Component("mysql")
@Scope("prototype")
public class MysqlAction extends MyActionSupport implements ModelDriven<FileVO> {
    private static MysqlOperation mo = new MysqlOperation();
    private HttpServletRequest request = ServletActionContext.getRequest();
    private final FileVO fileVO = new FileVO();
    private static String hostName = "localhost";
    private static String dataBase = "medicine";
    private static String userName = "root";
    private static String password = "root";
    private static String outFilePath = "/file/sql/";
    private static String mysqlBinUrl = "C:/Program Files/MySQL/MySQL Server 5.5/bin/";

    private final static Logger logger = Logger.getLogger(MysqlAction.class);

    public String backupMysqlDatabase() {

        /** 得到保存目录的真实路径 **/
        String saveFilePathDir = request.getSession().getServletContext().getRealPath(outFilePath);
        // 得到备份文件的目录的真实路径
        File dir = new File(saveFilePathDir);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        saveFilePathDir = saveFilePathDir + "\\Medicine.sql";
        try {
            mo.backupMysqlDatabase(mysqlBinUrl, hostName, dataBase, userName,
                    password, saveFilePathDir);
        } catch (Exception e) {
            fileVO.setResultMessage("系统备份失败，请查看后台参数设置。");
            logger.error(e);
            return ERROR;
        }
        fileVO.setResultMessage("系统成功备份数据库！");
        logger.trace("the database backup success!");
        return SUCCESS;
    }

    public String resumeMysqlDatabase() {
        /** 得到保存目录的真实路径 **/
        String saveFilePathDir = request.getSession().getServletContext().getRealPath(outFilePath);
        // 得到备份文件的目录的真实路径
        File dir = new File(saveFilePathDir);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        saveFilePathDir = saveFilePathDir + "\\Medicine.sql";

        try {
            mo.resumeMysqlDatabase(mysqlBinUrl, hostName, dataBase, userName,
                    password, saveFilePathDir);
        } catch (Exception e) {
            e.printStackTrace();
            fileVO.setResultMessage("系统还原失败，请查看后台参数设置。");
            logger.error(e);
            return ERROR;
        }
        fileVO.setResultMessage("系统成功还原数据库！");
        logger.trace("the database resume success!");
        return SUCCESS;
    }

    @Override
    public FileVO getModel() {
        return fileVO;
    }
}
